import { childrenProps, BasicForm, FormKeys } from '@/components/ProForm/interface/index';
import { ProTableValue } from '@/interface/public';

import { defaultStyle } from '@/basic/style';
import { PermissionInterface } from '@/api/interface/auth/permission';

export function useAddForm(proTableBox: ProTableValue) {
  let addForm = reactive<BasicForm<PermissionInterface.ReqSave>>({
    form: {
      customApiUrl: null,
      apiType: null,
      id: null,
      name: '',
      remark: '',
      actionType: null,
      sort: null,
      pid: 0,
      path: '',
      pathName: '',
      componentPath: '',
      redirect: '',
      metaIcon: '',
      apiUrl: '',
      metaTitle: '',
      metaActiveMenu: '',
      metaIsLink: '',
      metaIsHide: null,
      metaIsFull: null,
      metaIsAffix: null,
      metaIsKeepAlive: null,
      metaFlag: '',
      metaRole: '',
      systemId: null
    },
    title: '',
    visible: false,
    options: [
      {
        label: 'id',
        prop: 'id',
        hide: true,
        type: 'input',
        defaultValue: ''
      },
      {
        type: 'input',
        label: '权限名称',
        hide: false,
        prop: 'name',
        defaultValue: '',
        rules: [{ required: true, message: '请输入权限名称', trigger: 'blur' }]
      },
      {
        type: 'select',
        label: '权限类型',
        hide: false,
        prop: 'actionType',
        defaultValue: 'search',
        children: operateTypeStatus,
        rules: [{ required: true, message: '请选择操作类型', trigger: 'blur' }],
        changeMethod: () => changeActionType()
      },

      {
        type: 'input',
        label: '排序',
        hide: false,
        defaultValue: 0,
        prop: 'sort'
      },

      {
        type: 'input',
        label: '路由路径',
        hide: true,
        defaultValue: '',
        children: [],
        prop: 'path',
        inputMethod: () => {
          const { path } = addForm.form;
          Object.assign(addForm.form, {
            pathName: convertPathToCamelCase(path),
            componentPath: path ? `${path}/index` : ''
          });
        }
      },

      {
        type: 'input',
        label: '路由名称',
        hide: true,
        defaultValue: '',
        prop: 'pathName'
      },
      {
        type: 'input',
        label: '组件路径',
        hide: true,
        defaultValue: '',
        prop: 'componentPath'
      },
      {
        type: 'input',
        label: '重定向地址',
        hide: true,
        defaultValue: '',
        prop: 'redirect'
      },
      {
        type: 'input',
        label: '图标',
        hide: true,
        defaultValue: '',
        prop: 'metaIcon'
      },
      {
        type: 'select',
        label: '后端接口类型',
        hide: false,
        prop: 'apiType',
        defaultValue: 2,
        attrs: {
          clearable: false
        },
        children: [
          {
            type: 'option',
            label: '自定义',
            value: 1
          },
          {
            type: 'option',
            label: '选择',
            value: 2
          }
        ],
        changeMethod: form => {
          const flag = form.apiType === 2;
          console.log(form.apiType, 'form.apiType');

          formChangeItemStatus(addForm, ['customApiUrl'], flag, 'hide');
          formChangeItemStatus(addForm, ['apiUrl'], !flag, 'hide');
        }
      },
      {
        type: 'input',
        label: '自定义后端Api',
        hide: true,
        prop: 'customApiUrl',
        defaultValue: ''
      },
      {
        type: 'cascader',
        label: '后端接口地址',
        hide: false,
        defaultValue: '',
        prop: 'apiUrl',
        attrs: {
          options: [],
          clearable: true
        },
        changeMethod: form => {
          const { apiUrl } = form || {};

          if (apiUrl.length === 2) {
            const apiName = apiUrl[0];
            const children = formGetChildren(addForm, ['pid', 'apiUrl']);
            const { value } = children.get('pid').find(item => item.label === apiName) || {};
            if (value) {
              addForm.form.pid = value;
            }

            const label = arrTreeFindLabel(children.get('apiUrl'), apiUrl[1]);
            console.log(label, '标签', children.get('apiUrl'), apiUrl[1]);
            addForm.form.name = label;
          }
        }
      },
      {
        type: 'select',
        label: '父级',
        hide: false,
        prop: 'pid',
        defaultValue: '',
        children: [],
        attrs: {
          clearable: true
        }
      },
      {
        type: 'input',
        label: '路由标题',
        hide: true,
        defaultValue: '',
        prop: 'metaTitle'
      },
      {
        type: 'input',
        label: '高亮菜单路径',
        hide: true,
        defaultValue: '',
        prop: 'metaActiveMenu'
      },
      {
        type: 'input',
        label: '路由外链地址',
        hide: true,
        defaultValue: '',
        prop: 'metaIsLink'
      },
      {
        type: 'select',
        label: '在菜单中隐藏',
        hide: true,
        defaultValue: 0,
        prop: 'metaIsHide',
        children: yesOrNoStatus
      },
      {
        type: 'select',
        label: '固定在标签页',
        hide: true,
        defaultValue: 0,
        prop: 'metaIsAffix',
        children: yesOrNoStatus
      },
      {
        type: 'select',
        label: '路由是否缓存',
        hide: true,
        defaultValue: 0,
        prop: 'metaIsKeepAlive',
        children: yesOrNoStatus
      },
      {
        type: 'input',
        label: '其他标识',
        hide: true,
        defaultValue: '',
        prop: 'metaFlag',
        children: yesOrNoStatus
      },
      {
        type: 'input',
        label: '路由权限',
        hide: false,
        defaultValue: '',
        prop: 'metaRole'
      },
      {
        type: 'select',
        label: '所属系统',
        hide: true,
        defaultValue: '',
        prop: 'systemId',
        children: []
      },
      {
        type: 'input',
        label: 'remark',
        defaultValue: '',
        hide: false,
        prop: 'remark',
        attrs: {
          style: defaultStyle
        }
      }
    ]
  });

  /**
   * 根据路径转为驼峰命名
   */
  const convertPathToCamelCase = path => {
    // 使用正则表达式将斜杠和斜杠后的第一个单词（直到下一个斜杠或字符串结束）作为一个匹配项
    const parts = path.split('/').map((part, index, array) => {
      if (index !== 0) {
        return part.charAt(0).toUpperCase() + part.slice(1).toLowerCase();
      }
      return part;
    });

    return parts.join('');
  };

  const changeActionType = () => {
    const { actionType } = addForm.form || {};
    const flag = actionType === 'button' || actionType === 'search' || actionType === 'public';

    // 按钮和查询时不需要填写的字段
    const fields: FormKeys<PermissionInterface.ReqSave>[] = [
      'path',
      'pathName',
      'componentPath',
      'redirect',
      'metaIcon',
      'metaTitle',
      'metaActiveMenu',
      'metaIsLink',
      'metaIsHide',
      'metaIsAffix',
      'metaIsKeepAlive',
      'metaFlag'
    ];

    formChangeItemStatus(addForm, fields, flag, 'hide');

    // 对于选择自定义口后端接口后再次打开恢复默认显示

    // 显示的字段
    const displayFields: FormKeys<PermissionInterface.ReqSave>[] = ['apiUrl'];
    formChangeItemStatus(addForm, displayFields, false, 'hide');

    // 如果是菜单 隐藏掉后端隐藏api接口
    const flag2 = actionType === 'menu' || actionType === 'menu_public';
    formChangeItemStatus(addForm, ['customApiUrl', 'apiUrl', 'apiType'], flag2, 'hide');

    // 默认不显示自定义后端接口
    const hideFields: FormKeys<PermissionInterface.ReqSave>[] = ['customApiUrl'];
    formChangeItemStatus(addForm, hideFields, true, 'hide');
  };

  const saveAddForm = async (form: PermissionInterface.ReqSave) => {
    const params = { ...form };
    const { apiUrl, apiType, customApiUrl } = form || {};
    params.apiUrl = apiUrl?.length ? apiUrl[apiUrl.length - 1] : '';

    // 设置为自定义url
    if (apiType === 1) {
      params.apiUrl = customApiUrl;
    }

    await permissionSave(params);
    addForm.visible = false;
    elMessage();

    proTableBox.value?.getTableList();
  };

  let treeObj = reactive<{ [key: string]: childrenProps[] }>({
    pidTreeData: [],
    apiTreeData: []
  });

  const getAddFormChildren = async () => {
    const res = await promiseAllApi([
      permissionFlattenTree(),
      permissionFindListPermission(),
      apiAuthScannerTree(),
      apiBasicScannerTree()
    ]);
    const treeData = arrTransitionTreeData<PermissionInterface.ResFlattenTree>(res[0], 'name', 'id');

    const selectId: Array<string> = arrLiftField<PermissionInterface.ReqSave>(res[1], 'apiUrl');

    const apiAuthTreeData = arrTransitionTreeData<PermissionInterface.ResFlattenTree>(res[2], 'id', 'path');
    const apiBasicTreeData = arrTransitionTreeData<PermissionInterface.ResFlattenTree>(res[3], 'id', 'path');

    const apiTreeData = [...apiAuthTreeData, ...apiBasicTreeData];

    signBindingPermission(apiTreeData, selectId);

    treeObj.pidTreeData = treeData;
    treeObj.apiTreeData = apiTreeData;

    const children: Map<FormKeys<PermissionInterface.ReqSave>, childrenProps[]> = new Map();
    children.set('pid', treeData);
    children.set('apiUrl', apiTreeData);
    console.log(apiTreeData, 'apiTreeData');

    formSetChildren(addForm, children);
  };

  /**
   * 标记已绑定权限
   */
  const signBindingPermission = (apiTreeData: childrenProps[], selectId: Array<string>) => {
    apiTreeData.forEach(element => {
      for (let item of element.children) {
        if (selectId.includes(item.value as string)) {
          item.label += `(已绑定)`;
        }
      }
      dataTreeSort(element.children);
    });
  };

  /**
   * 排序
   */
  const dataTreeSort = (apiTreeData: childrenProps[]) => {
    apiTreeData.sort((obj1, obj2) => {
      // 如果 obj1 的 a 字段包含“已绑定”，‌并且 obj2 的 a 字段不包含“已绑定”
      if (obj1.label.includes('已绑定') && !obj2.label.includes('已绑定')) {
        return 1; // 把 obj1 放在后面
      }
      // 如果 obj2 的 a 字段包含“已绑定”，‌并且 obj1 的 a 字段不包含“已绑定”
      if (!obj1.label.includes('已绑定') && obj2.label.includes('已绑定')) {
        return -1; // 把 obj2 放在后面，‌但由于是逆序比较，‌所以实际上是把 obj1 放在前面
      }
      return 0; // 如果两者都没有“已绑定”，‌则保持原顺序
    });
  };

  return { addForm, saveAddForm, treeObj, getAddFormChildren, changeActionType };
}
